package com.tisson;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import com.tisson.action.ActionSup;

public class ExcelWriteAction extends ActionSup {
	private String checkbox[];

	@SuppressWarnings("unchecked")
	public String write() {
		List list = (List) request.getSession().getAttribute("list");
		String combo[][] = stringSplit(checkbox);
		String[] titleName = combo[1];
		String[] param = combo[0];
		ExcelWriter excelWriter = new ExcelWriter();
		try {
			excelWriter = new ExcelWriter(response.getOutputStream());

			excelWriter.createRow(0);
			for (int k = 0; k < titleName.length; k++) {
				excelWriter.setCell(k, titleName[k]);
			}
			for (int j = 0; j < list.size(); j++) {
				Class cls = list.get(j).getClass();
				Field[] fields = cls.getDeclaredFields();
				excelWriter.createRow(j + 1);
				for (int i = 0; i < param.length; i++) {
					String getMethodName = "get"
							+ param[i].substring(0, 1).toUpperCase()
							+ param[i].substring(1);
					Method getMethod = cls.getMethod(getMethodName,
							new Class[] {});
					Object value = getMethod.invoke(list.get(j),
							new Object[] {});
					excelWriter.setCell(i, value.toString());
				}
			}
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success";
	}

	public String[][] stringSplit(String[] s) {
		String[][] rst = new String[2][s.length];
		for (int i = 0; i < s.length; i++) {
			String[] t = s[i].split("_");
			rst[0][i] = t[0];
			rst[1][i] = t[1];
		}
		return rst;
	}

	public String[] getCheckbox() {
		return checkbox;
	}

	public void setCheckbox(String[] checkbox) {
		this.checkbox = checkbox;
	}
}
